package cn.stimd.spring.beans.factory.support;

import cn.stimd.spring.beans.BeanUtils;
import cn.stimd.spring.beans.BeansException;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName) throws BeansException {
        try {
            return BeanUtils.instantiateClass(bd.getBeanClass());
        }catch (Exception e){
            throw new BeansException("使用无参构造器创建实例[" + beanName + "]失败", e);
        }
    }


    @Override
    public Object instantiate(RootBeanDefinition bd, String beanName, Constructor<?> ctor, Object... args) throws BeansException {
        try {
            return BeanUtils.instantiateClass(ctor, args);
        }catch (Exception e){
            throw new BeansException("使用有参构造器创建实例[" + beanName + "]失败", e);
        }
    }


    @Override
    public Object instantiate(String beanName, Object factoryBean, Method factoryMethod, Object... args) throws BeansException {
        try {
            ReflectionUtils.makeAccessible(factoryMethod);
            return factoryMethod.invoke(factoryBean, args);
        } catch (Exception e) {
            throw new BeansException("使用工厂方法[" + factoryMethod.getName() + "]创建实例[" + beanName + "]失败", e);
        }
    }
}
